package com.web.music.impl;

import java.io.InputStream;
import java.util.Map;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpHost;
import org.apache.log4j.Logger;


import com.web.music.interfaces.HTTPClient;

/**
 * HTTP client implementation which uses ApacheHttpClient API.
 * See http://hc.apache.org/httpclient-3.x/
 * 
 * TODO [done] 
 * Your task is to implement data downloading from remote URL.
 * Suggested way is to use ApacheHttpClient API.
 * However you are free to use any framework and also to change HTTPClient interface.
 */

public class ApacheHTTPClient implements HTTPClient {

	// TODO [done]
	// You need to provide application user a way to define proxy settings.
	// You task is to handle it in your implementation.
	static Logger logger = Logger.getLogger(DomXmlParser.class.getName());	
	private Map<String, String> configurationSettings;	

	public InputStream download(String url){
		InputStream xmlFile = null;
		HttpClient httpclient = new DefaultHttpClient();

		String proxyHost = null;
		try {
			proxyHost = configurationSettings.get("http.proxyHost");
		}
		catch (Exception e){
			proxyHost = null;
		}
		int proxyPort = 0; 
		try{
			proxyPort = Integer.parseInt(configurationSettings.get("http.proxyPort"));
		}
		catch (Exception e){
			proxyPort = 0;			
		}

                
        if (proxyHost!=null && proxyPort!=0){
        	final HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http");
        	httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
		HttpGet httpget = new HttpGet(url); 
		logger.info("Executing request " + httpget.getURI());

		try {
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				if (entity != null) {
					logger.info("File size: " + entity.getContentLength());
					xmlFile = entity.getContent();
				}
			}
		}
		catch ( Exception e)
		{
			logger.fatal(e.getMessage());
		}
		return xmlFile;
		//throw new RuntimeException("ApacheHTTPClient is not implemented");
	}	

	public Map<String, String> getConfigurationSettings() {
		return configurationSettings;
	}

	public void setConfigurationSettings(Map<String, String> configurationSettings) {
		this.configurationSettings = configurationSettings;
	}
}
